package com.skymobi.cassandra.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.cassandra.utils.FileUtils;
import org.apache.thrift.transport.TTransportException;

import com.skymobi.cassandra.service.CassandraClientTest;
import com.skymobi.cassandra.service.EmbeddedCassandraService;

public class EmbeddedServerHelper {
	public static EmbeddedCassandraService cassandra;
	public static final String TMP = "tmp";

	public void setUp() throws IOException, TTransportException {
		// delete tmp dir first
		rmdir(TMP);
		// make a tmp dir and copy storag-conf.xml and log4j.properties to it
		copy("/storage-conf.xml", TMP);
		copy("/log4j.properties", TMP);
		System.setProperty("storage-config", TMP);

		CassandraServiceDataCleaner cleaner = new CassandraServiceDataCleaner();
		cleaner.prepare();
		cassandra = new EmbeddedCassandraService();
		cassandra.init();
		Thread t = new Thread(cassandra);
		t.setDaemon(true);
		t.start();
	}

	public void tearDown() throws IOException {
		CassandraServiceDataCleaner cleaner = new CassandraServiceDataCleaner();
		cleaner.cleanupDataDirectories();
		rmdir(TMP);
	}

	private static void copy(String resource, String directory)
			throws IOException {
		mkdir(directory);
		InputStream is = CassandraClientTest.class
				.getResourceAsStream(resource);
		String fileName = resource.substring(resource.lastIndexOf("/") + 1);
		File file = new File(directory + System.getProperty("file.separator")
				+ fileName);
		OutputStream out = new FileOutputStream(file);
		byte buf[] = new byte[1024];
		int len;
		while ((len = is.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		out.close();
		is.close();
	}

	private static void mkdir(String dir) throws IOException {
		FileUtils.createDirectory(dir);
	}

	private static void rmdir(String dir) throws IOException {
		File dirFile = new File(dir);
		if (dirFile.exists()) {
			FileUtils.deleteDir(new File(dir));
		}
	}

}
